package com.csii.adhoc.util.myabtisplus;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csii.adhoc.annotation.Excel;
import com.csii.adhoc.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @description: QueryWrapper工具类
 * @author: panChuanJiang
 * @create: 2021-07-13 15:32
 */
public class QueryWrapperUtils {
    /**
     * mybatisPlus工具类、根据实体类获取queryWrapper，只适用于等值查询
     *
     * @param t            dto实体类
     * @param queryWrapper queryWrapper
     * @param <T>          泛型
     * @return 包装后的实体类
     */
    public static <T> QueryWrapper<T> getEqQueryWrapperFromDto(T t, QueryWrapper<T> queryWrapper) {
        if (t == null) {
            return queryWrapper;
        }
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field f : fields) {
            try {
                if (f.getAnnotation(Excel.class) == null) {
                    continue;
                }
                f.setAccessible(true);
                Object val = f.get(t);
                if (val != null) {
                    if (val instanceof String && "".equals(val.toString())){
                        continue;
                    }
                    queryWrapper.eq(StringUtils.humpToUnderscore(f.getName()), val);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return queryWrapper;
    }
}
